package com.heima.user.Interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户ID
        String userId = request.getHeader("userId");
        // 如果用户ID不为空，则创建一个WmUser对象并设置用户ID
        if (!(ObjectUtils.isEmpty(userId))){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            // 将用户信息存入ThreadLocal
            AppThreadLocalUtil.setUser(apUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtil.remove();
    }
}
